package com.xunji.xunji.module.trace.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.huanxiao.base.base.BaseActivity;
import com.huanxiao.base.util.AlertDialogUtil;
import com.huanxiao.base.util.FileHelper;
import com.huanxiao.base.util.PathHelper;
import com.huanxiao.base.view.GridViewForScrollView;
import com.huanxiao.util.DateHelper;
import com.huanxiao.util.GlideHelper;
import com.xunji.xunji.R;
import com.xunji.xunji.db.dao.TraceImageDao;
import com.xunji.xunji.module.trace.util.PointConst;
import com.xunji.xunji.module.trace.bean.TagInfo;
import com.xunji.xunji.module.trace.dao.TraceImage;
import com.xunji.xunji.module.trace.ui.adapter.TagAdapter;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * Created by Paul on 2017/2/14.
 */

public class TracePhotoEditActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_IMAGE_FROM_CAMERA = 1;
    private static final int REQUEST_CODE_CROP_IMAGE = 3;//启动裁剪编辑

    private static final String EXTRA_FILE_PATH = "EXTRA_FILE_PATH";
    private static final String EXTRA_LOGINTUDE = "EXTRA_LOGINTUDE";
    private static final String EXTRA_LATITUDE = "EXTRA_LATITUDE";
    private static final String EXTRA_TRACE_ID = "EXTRA_TRACE_ID";
    private ImageView ivPicture;
    private EditText etDesc;
    private GridViewForScrollView gridTag;
    private String filePath;
    private double longitude;
    private double latitude;
    private Integer traceId;

    private Button btnCancel;
    private Button btnConfirm;
    private TagAdapter adapter;

    private ImageView ivDelete;

    private List<TagInfo> tagInfoList = PointConst.getTagInfoList();

    private TraceImageDao traceImageDao;
//    private String[] tags = {"停", "票", "WC", "休", "吃", "住", "水", "营",
//            "爬", "降", "攀", "租", "火", "烤", "滑", "补", "引", "医", "架",
//            "AED", "影", "景", "店", "捕", "购", "索", "观"};
//    private Map<String,Integer> iconMap = PointConst.iconMap();



    private TraceImage traceImage;

    private int tagPosition;

    public static void start(Context context, String filePath, double latitude, double longitude, int traceId) {
        Intent starter = new Intent(context, TracePhotoEditActivity.class);
        starter.putExtra(EXTRA_FILE_PATH, filePath);
        starter.putExtra(EXTRA_LATITUDE, latitude);
        starter.putExtra(EXTRA_LOGINTUDE, longitude);
        starter.putExtra(EXTRA_TRACE_ID, traceId);
        context.startActivity(starter);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_trace_photo_edit;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    public void initBundleExtras(Bundle extras) {
        traceImage = new TraceImage();
        filePath = extras.getString(EXTRA_FILE_PATH);
        longitude = extras.getDouble(EXTRA_LOGINTUDE);
        latitude = extras.getDouble(EXTRA_LATITUDE);
        traceId = extras.getInt(EXTRA_TRACE_ID);

        traceImage.setImagePaths(filePath);
        traceImage.setLongitude(longitude);
        traceImage.setLatitude(latitude);
        traceImage.setTraceId(traceId);
    }



    @Override
    protected void initView() {

        btnCancel = fvById(R.id.btn_cancel);
        btnConfirm = fvById(R.id.btn_confirm);
        ivPicture = fvById(R.id.iv_picture);
        etDesc = fvById(R.id.et_desc);
        gridTag = fvById(R.id.grid);

        ivDelete = fvById(R.id.iv_delete);

        Log.e("HPG", filePath);

        GlideHelper.displayFile(filePath, ivPicture);
        showDelete(true);



        adapter = new TagAdapter(tagInfoList, this);
        gridTag.setAdapter(adapter);

    }

    @Override
    protected void initListener() {
        btnCancel.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        gridTag.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tagPosition = position;
                for (int i = 0; i < tagInfoList.size(); i++) {
                    tagInfoList.get(i).setSelect(false);
                }

                tagInfoList.get(tagPosition).setSelect(true);
                adapter.setDataChanged(tagInfoList);


            }
        });

        ivDelete.setOnClickListener(this);
        ivPicture.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        traceImageDao = new TraceImageDao(this);
    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case REQUEST_CODE_IMAGE_FROM_CAMERA:
                Uri tempPicUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg"));
                cropImage(tempPicUri);
                break;
            case REQUEST_CODE_CROP_IMAGE:
                try {
                    Bitmap mPhotoBitmap = data.getParcelableExtra("data");
                    if (mPhotoBitmap == null) {
                        Uri uri = data.getData();
                        mPhotoBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    }
                    if (mPhotoBitmap == null) {
                        return;
                    }
                    String fileName = "point_" + System.currentTimeMillis() + ".png";
                    FileHelper.saveBitmapToFile(mPhotoBitmap, fileName);
                    filePath = PathHelper.getLocalProductImagePath() + fileName;

                    GlideHelper.displayFile(filePath, ivPicture);
                    showDelete(true);
                    traceImage.setImagePaths(filePath);
//                    TracePhotoEditActivity.start(this, PathHelper.getLocalProductImagePath() + fileName, mCurrentLatlng.latitude, mCurrentLatlng.longitude, traceManager.getTraceId());

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void cropImage(Uri tempPicUri) {
        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(tempPicUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                AlertDialogUtil.showDialog(this, "提示", "确定退出编辑吗？", "取消", "确定", null, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                break;
            case R.id.btn_confirm:
                traceImage.setDate(new Date());
                traceImage.setId(DateHelper.getCurrentSecond());
                traceImage.setContent(etDesc.getText().toString());
                traceImage.setTag(tagInfoList.get(tagPosition).getTitle());
                traceImageDao.saveTraceImage(traceImage);
                sendEventBus(EVENT_TRACE_IMAGE_SAVE, traceImage);
                finish();
                break;


            case R.id.iv_delete:
                GlideHelper.display(R.drawable.ic_camera, ivPicture);
                showDelete(false);
                break;

            case R.id.iv_picture:
                if (ivDelete.getVisibility() == View.GONE) {
                    getFromCamera();
                }
                break;
        }
    }

    private void getFromCamera() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg"));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CAMERA);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void showDelete(boolean isshow) {
        ivDelete.setVisibility(isshow ? View.VISIBLE : View.GONE);
    }
}
